// mircoApp/meituan_refund/detail/detail.js
import {host as imgPath} from "../../../host.js";const skinBehavior = require('../../../utils/themeSkin/skinBehavior');
const app = getApp();
Page({
  behaviors: [skinBehavior],

  /**
   * 页面的初始数据
   */
  data: {
    mini_link:"",
    text_href:"",
    radio:"1",
    start_time:"",
    end_time:"",
    couponPackDetail:{},
    deliverablePoiInfo:{},
    show_stroe:false,
    imgPath: app.globalData.imgPath,
    wechat_app_id:"",
    link:"",
    utils_text:"",

    share_popup: false,
    posterShow: false,
    isFrontCanvas: true, //是否前端控制生成海报，false为后端生成
    posterImg: null,

    share_reward:{},
    order_reward:{},

    detail: {},
    CarouseList: [],
    imagUrl: imgPath,
    address: "",
    share_flag:false,
    service_QRcode: "",
    brandInfo:{},
    service_mobile: "",
    cservice: "",
    isShowChat: false,

    show_popup: false,
    group_buy_code:"",
    cityId: "",
    cate_id: "",
    lng: "",
    lat: "",
    dealid: "",

    dealBaseInfo: {},
    couponInfo: {},
    shopInfo: {},
    defaultPic: '',
    share_amount: 0,
    amount: 0,

    group_code: {},
    language: "",
    show1: false,

    city_name: "",
    ids:"",
  },

  /**
   * 生命周期函数--监听页面加载
   */
 async onLoad(options) {
    let language = wx.getStorageSync('langIndex');
    let address_point = wx.getStorageSync("address-point");
    this.setData({
      'language': language.en,
    });
    if(address_point){
      this.data.lng = address_point.point.lng;
      this.data.lat = address_point.point.lat;
    }
    if(options.ids){
      this.setData({ids:options.ids})
    }
    if(options.id){
      this.setData({id: options.id});
    }else if(options.scene){ //扫码进入
      let scene = decodeURIComponent(options.scene);
      // 扫码进入
      if (scene) {
        let info_arr = scene.split(',');
        console.log(
          info_arr,'info_arr=='
        );
        // this.data.id = info_arr[0];
        this.setData({id:info_arr[0],ids:info_arr[1]})
      }
    }
   await this.get_link();
   await this.getData();
  },
  radioChange(e) {
    this.setData({
      radio: e.detail
    })
  }, onCopy(e) {
    let data  = e.currentTarget.dataset.copy;
    console.log(e,'data===')
    wx.setClipboardData({
      data,
      success(res) {
        wx.showToast({
          title: "复制成功",
          icon: "none",
          duration: 3000,
        });
      },
      fail() {
        wx.showToast({
          title: "复制失败",
          icon: "none",
          duration: 3000,
        });
      },
    });
   
  },
  open_popup(){
      this.setData({share_flag:true});
  },
  format_time(time){
    if(time){
        let _str = (time+'').length<13?(time+''+'000'):time;
        let date = new Date(_str*1);
        let month = date.getMonth()+1<10?'0'+(date.getMonth()+1):date.getMonth()+1;
        let day = date.getDate()<10?'0'+date.getDate():date.getDate();
        return `${date.getFullYear()}.${month}.${day}`;
    }
    return '';
  },
  async get_link(){
    let json = {
      url: app.getNetAddresss('plugin.meituan-group-buy.frontend.good.generate-link'),
      data:{sku_view_id:this.data.id,ids:this.data.ids}
    };  
   let {data,result,msg} =  await app._getNetWork(json)
    if(result==0){
      app.tips(msg);
    }else{
      this.data.wechat_app_id = data.data.wechat_app_id;
      this.setData({
        link:data.data.link,
        mini_link:data.data.mini_link,
        group_buy_code:data.data.group_buy_code
      })
    }
  },
  popup_close(){
    this.setData({share_flag:false});
  },
  get_city_id(name) {
    app._postNetWork({
      url:app.getNetAddresss("plugin.meituan-group-buy.frontend.good.city"),
      data:{name},
      success:resdata=>{
        let {result,msg,data} = resdata.data;
        if(result!==1){
          return app.tips(msg);
        }
        let city_id;
        for (let item in data) {
          city_id = data[item][0].id;
        }
        this.setData({city_id})
        wx.setStorageSync('meituan_city_id', city_id)
        this.getData();
      }
    })
  },
  closePop() {
    this.setData({
      posterShow: false
    })
  },
  setPosterShow() {
    this.setData({
      posterShow: true
    })
  },
  goto() {
    wx.navigateTo({
      url: '/packageI/citypickerPage/citypickerPage?plu=meituan&path=detail'
    })
  },
  buyOrder() {
    wx.navigateToMiniProgram({
      appId:this.data.wechat_app_id,
      path:this.data.link
    })
  },
  showPop() {
    this.setData({
      show1: true
    })
  },
  getData() {
    let json = {
      sku_view_id: this.data.id,
      ids:this.data.ids
    }

    if((this.data.lng*1)>0&&(this.data.lat*1)>0){
      json.longitude=this.data.lng*1;
      json.latitude=this.data.lat*1;
    }

    app._getNetWork({
      url: app.getNetAddresss('plugin.meituan-group-buy.frontend.good.good'),
      data: json,
      success: resdata => {
        let {
          result,
          msg,
          data
        } = resdata.data;
        if (result) {
          let {cservice,group_code} = data.good_detail;
          let {
              couponPackDetail,
              deliverablePoiInfo,
              reward,
              brandInfo
          } = data.data[0];

          for (const key in deliverablePoiInfo) {
            if (deliverablePoiInfo[key]) {
              this.setData({show_stroe:true});
            }
          }
          
          let start_time = this.format_time(couponPackDetail.startTime)
          let end_time = this.format_time(couponPackDetail.endTime)
          let utils_text = '';
          if(couponPackDetail.saleVolume.indexOf('热销')>=0){
            utils_text = couponPackDetail.saleVolume;
          }else{
            utils_text = '已售'+couponPackDetail.saleVolume;
          }
          let text_href =  `${couponPackDetail.name}\n【现价】${couponPackDetail.sellPrice }元\n【原价】${couponPackDetail.originalPrice}元\n【有效期】${start_time}-${end_time}\n【下单链接】\n${this.data.mini_link}`
          this.setData({
            text_href,
            brandInfo,
            utils_text,
            start_time,
            end_time,
            couponPackDetail,
            deliverablePoiInfo,
            cservice,
            group_code,
            reward
          })

        } else {
          app.tips(msg);
        }
      }
    })
  },

  gotoHome() {
    wx.navigateTo({
      url: '/mircoApp/meituan_refund/index/index',
    })
  },
  // 群活码跳转
  toGroupCode() {
    if (this.data.group_code.jump_mode === 'home') {
      wx.reLaunch({
        url: '/packageE/groupCode/groupCode',
      });
    } else if (this.data.group_code.code_mini_url) {
      wx.navigateTo({
        url: this.data.group_code.code_mini_url
      });
    }
  },
  goToWXAdress() {

   let point = app.BMapTransqqMap(parseFloat(this.data.lng), parseFloat(this.data.lat));
   if(point){
    wx.openLocation({
      latitude: point.lat,
      longitude: point.lng,
      name: this.data.deliverablePoiInfo.poiName,
      scale: 18
    });
   }
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */

  onShareAppMessage() {
    return {
      title:"商品详情",
      path:"/mircoApp/meituan_refund/detail/detail?id="+this.data.id+'&ids='+this.data.ids,
      success: function(res){
　　　　　　// 转发成功之后的回调
　　　　　　if(res.errMsg == 'shareAppMessage:ok'){
　　　　　　}
　　　　},
　　　　fail: function(){
　　　　　　// 转发失败之后的回调
　　　　　　if(res.errMsg == 'shareAppMessage:fail cancel'){
　　　　　　　　// 用户取消转发
　　　　　　}else if(res.errMsg == 'shareAppMessage:fail'){
　　　　　　　　// 转发失败，其中 detail message 为详细失败信息
　　　　　　}
　　　　},
　　　　complete(){
　　　　　　// 转发结束之后的回调（转发成不成功都会执行）
　　　　}
    }
  },
})